package com.example.mq1.mqserver.core;

import com.example.mq1.common.ConsumerEnv;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 消息队列
 */
public class MSGQueue {

    private String queueName;
    //是否持久化
    private boolean durable = false;
    //是否被消费者独占
    private boolean exclusive = false;
    //自动删除
    private boolean autoDelete = false;
    //额外参数
    private Map<String, Object>  arguments = new HashMap<>();
    //表示当前队列和哪些消费者绑定
    private List<ConsumerEnv> consumerEnvList = new ArrayList<>();
    //表示当前轮询到当前消费者的下标
    private AtomicInteger consumerIndex = new AtomicInteger(0);

    public void addConsumerEnv(ConsumerEnv consumerEnv) {
        consumerEnvList.add(consumerEnv);
    }

    /**
     * 按照轮询的方式来选择当前队列对应消费者
     * @return
     */
    public ConsumerEnv chooseConsumerEnv() {
        if(consumerEnvList.size() == 0) {
            return null;
        }
        int index = consumerIndex.get() % consumerEnvList.size();
        consumerIndex.incrementAndGet();
        return consumerEnvList.get(index);
    }


    public String getQueueName() {
        return queueName;
    }

    public void setQueueName(String queueName) {
        this.queueName = queueName;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isExclusive() {
        return exclusive;
    }

    public void setExclusive(boolean exclusive) {
        this.exclusive = exclusive;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    //这一组给数据库提供
    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String res = objectMapper.writeValueAsString(arguments);
            return res;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    public void setArguments(String argumentsJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(argumentsJson,
                    new TypeReference<Map<String, Object>>() {});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }


    //这一组提供给内部调用
    public Object getArguments(String key) {
        return arguments.get(key);
    }

    public void setArguments(String key, Object value) {
        arguments.put(key, value);
    }

    public void setArguments(Map<String, Object> map) {
        this.arguments = map;
    }
}
